<template>
  <div style="display: inline">
    <span @click="handleShow">
      <slot name="uploadLink">
        <el-button :icon="Finished" size="small" type="primary">导入</el-button>
      </slot>
    </span>
    <vab-dialog
      v-model="dialogFormVisible"
      :before-close="handleClose"
      :close-on-click-modal="true"
      show-fullscreen
      :title="title"
      width="50%"
    >
      <div class="upload">
        <div class="download" style="margin-bottom: 10px">
          <el-table :data="uploadData">
            <el-table-column label="模板" prop="name" />
            <el-table-column align="center" label="操作" width="100">
              <download-template :templatefilename="templatefilename">
                <el-button :icon="Download" size="small" type="primary"> 下载 </el-button>
              </download-template>
            </el-table-column>
          </el-table>
        </div>
        <el-upload
          ref="uploadRef"
          :accept="accept"
          :auto-upload="false"
          :before-upload="handleBeforeUpload"
          :file-list="fileList"
          :limit="limit"
          :multiple="false"
          :on-change="handleChange"
          :on-exceed="handleExceed"
          :on-remove="handleRemove"
        >
          <el-button :icon="Upload" size="small" type="primary"> 选择文件 </el-button>
        </el-upload>
      </div>
      <template #footer>
        <div style="position: relative; padding-right: 15px; text-align: right">
          <el-button :loading="loading" type="success" @click="handleUpload"> 确认导入 </el-button>
          <el-button type="info" @click="handleClose">关闭</el-button>
        </div>
      </template>
    </vab-dialog>
  </div>
</template>

<script>
import { Download, Upload } from "@element-plus/icons-vue";
import VabDialog from "@/plugins/VabDialog/index.vue";
import { uploadUrl } from "@/api/mains";
import { ElLoading } from "element-plus";
import DownloadTemplate from "@/plugins/upload/DownloadTemplate.vue";

export default defineComponent({
  name: "UploadDialog",
  components: {
    DownloadTemplate,
    VabDialog
  },
  props: {
    url: {
      type: String,
      default: "",
      required: true
    },
    templatefilename: {
      type: String,
      default: "",
      required: true
    },
    accept: {
      type: String,
      default: ""
    },
    limit: {
      type: Number,
      default: 1
    },
    size: {
      type: Number,
      default: 1024,
      required: true
    }
  },
  emits: {
    callbackupload: null
  },
  setup(props, { emit }) {
    const { proxy } = getCurrentInstance();
    const state = reactive({
      loading: false,
      title: "上传",
      uploadRef: null,
      tempurl: "templateFile",
      templatefilename: props.templatefilename,
      dialogFormVisible: false,
      fileList: [],
      uploadData: [{ name: props.templatefilename }],
      limit: "1",
      url: "",
      accept: "",
      size: 0
    });
    state.accept = ref(props.accept);
    state.url = ref(props.url);
    if (state.url.indexOf("/") < 0) {
      state.url = `${state.url}/importFile`;
    }

    state.limit = ref(props.limit);
    state.templatefilename = ref(props.templatefilename);
    state.size = ref(props.size);

    const handleChange = file => {
      if (file) {
        if (file.size > state.size) {
          proxy.$baseMessage(`文件大于${state.size}B`, "warning");
          //state['uploadRef'].uploadFiles.splice(0, 1)
          state["uploadRef"].handleRemove(file);
          return false;
        } else {
          state.fileList.push(file);
          return true;
        }
      }
      return false;
    };

    const handleBeforeUpload = rawFile => {
      //没触发该方法
      console.info(rawFile);
      return false;
    };

    const handleUpload = async () => {
      state.loading = true;
      if (state.fileList.length === 0) {
        proxy.$baseMessage("请选取文件", "warning");
        state.loading = false;
        return;
      } else {
        const loading = ElLoading.service({
          lock: true,
          text: "导入中，请稍候...",
          background: "rgba(0, 0, 0, 0.7)"
        });
        const formdata = new FormData();
        state.fileList.forEach(file => {
          formdata.append("upfile", file.raw);
        });
        const responseData = await uploadUrl(state.url, formdata);
        if (responseData.code == 200) {
          proxy.$baseMessage(responseData.msg, "success", false, "vab-hey-message-success");
        } else {
          /* proxy.$baseMessage(
              responseData.msg,
              'error',
              false,
              'vab-hey-message-error'
            ) */
        }
        state.fileList = [];
        emit("callbackupload", responseData);
        handleClose();
        state.loading = false;
        loading.close();
      }
    };

    const handleExceed = files => {
      if (state.limit == 1) {
        //替换当前的文件
        state.fileList = [];
        state.fileList.push(files[0]);
      } else {
        proxy.$baseMessage(
          `当前限制选择 ${state.limit} 个文件，本次选择了
                ${files.length}
                个文件`,
          "error",
          "vab-hey-message-error"
        );
      }
    };

    const handleRemove = (file, fileList) => {
      state.fileList = fileList;
    };

    const handleShow = () => {
      state.title = "导入";
      state.dialogFormVisible = true;
    };
    const handleClose = () => {
      state.fileList = [];
      state.dialogFormVisible = false;
    };

    return {
      ...toRefs(state),
      handleUpload,
      handleShow,
      handleClose,
      handleChange,
      handleExceed,
      handleRemove,
      handleBeforeUpload,
      Download,
      Upload,
      VabDialog
    };
  }
});
</script>

<style lang="scss" scoped>
.upload {
  height: 45vh;
  .upload-content {
    .el-upload__tip {
      display: block;
      height: 30px;
      line-height: 30px;
    }
    :deep() {
      .el-upload--picture-card {
        width: 128px;
        height: 128px;
        margin: 3px 8px 8px;
        border: 2px dashed #c0ccda;
      }
      .el-upload-list--picture {
        margin-bottom: 20px;
      }
      .el-upload-list--picture-card {
        .el-upload-list__item {
          width: 128px;
          height: 128px;
          margin: 3px 8px 8px;
        }
      }
    }
  }
}
.vab-dialog {
  display: inline;
}
.text-left {
  padding-left: 30px;
  text-align: left;
}
h3 {
  padding-bottom: 20px;
}
.cust_btn30 {
  padding-top: 30px;
  padding-bottom: 60px;
}
.text_fise {
  font-size: 16px;
}
.text_fise > div {
  padding-bottom: 20px;
}
</style>
